package cn.tnar.yunpark.util;

import java.io.UnsupportedEncodingException;

public class RC4Util {
	
	public static String HloveyRC4(String aInput,String aKey) 
    { 
        int[] iS = new int[256]; 
        byte[] iK = new byte[256]; 
        
        for (int i=0;i<256;i++) 
            iS[i]=i; 
            
        int j = 1; 
        
        for (short i= 0;i<256;i++) 
        { 
            iK[i]=(byte)aKey.charAt((i % aKey.length())); 
        } 
        
        j=0; 
        
        for (int i=0;i<255;i++) 
        { 
            j=(j+iS[i]+iK[i]) % 256; 
            int temp = iS[i]; 
            iS[i]=iS[j]; 
            iS[j]=temp; 
        } 
    
    
        int i=0; 
        j=0; 
        char[] iInputChar = aInput.toCharArray(); 
        char[] iOutputChar = new char[iInputChar.length]; 
        for(short x = 0;x<iInputChar.length;x++) 
        { 
            i = (i+1) % 256; 
            j = (j+iS[i]) % 256; 
            int temp = iS[i]; 
            iS[i]=iS[j]; 
            iS[j]=temp; 
            int t = (iS[i]+(iS[j] % 256)) % 256; 
            int iY = iS[t]; 
            char iCY = (char)iY; 
            iOutputChar[x] =(char)( iInputChar[x] ^ iCY) ;    
        } 
        
        return new String(iOutputChar);  
    }
	
	public static String EncryRC4(String sourceStr,String key){ 
		try {
	       return bytesToHexString(HloveyRC4(sourceStr, key).getBytes("utf-8"));
	   } catch (UnsupportedEncodingException e) {
	       e.printStackTrace();
	   }
	   return "";
	}
	
	public static String DecryRC4(String sourceStr,String key){
		sourceStr = HexToString(sourceStr);
		return HloveyRC4(sourceStr, key);
	}
	
	public static String HexToString(String s) {
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(
						s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}
	 
	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}
}
